package util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.jdom.Element;

import pojo.OnlineSocket;

public class GenerateHTML {
  public static Element generate(Map<String, OnlineSocket> onlineUsers, long startTime, boolean isOpenServer){

    //format the time
    String start;
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
      if(startTime == 0){
        start = " ";
      }else{
        start = sdf.format(new Date(startTime));
      }
    
    Element root = new Element("html");
    Element head = new Element("head");
    Element title = new Element("title");
    title.setText("Server Manager");
    head.addContent(title);
    root.addContent(head);
    
    Element body = new Element("body");
    Element h1 = new Element("h1");
    h1.setText("Server Manager");
    h1.setAttribute("style", "text-align:center; color:black");
    body.addContent(h1);
    
    Element div = new Element("div");
    div.setAttribute("style", "text-align:center");
    Element btnStart = genBtn("Start", "start");
    Element btnEnd = genBtn("End", "end");
    Element btnFresh = genBtn("Refresh", "");
    div.addContent(btnStart);
    div.addContent(btnFresh);
    div.addContent(btnEnd);
    
    Element pStart = new Element("p");
    pStart.setText("Start time: "+start);
    Element pState = new Element("p");
    if(isOpenServer == true){
    	pState.setText("Server is active!");
    }else{
    	pState.setText("Server is close!");
    }
    div.addContent(pStart);
    div.addContent(pState);
    body.addContent(div);
    
    Element div2 = new Element("div");
    div2.setAttribute("style","text-align:center");
    Element p3 = new Element("p");
    Element strong3 = new Element("strong");
    strong3.setText("online users: ");
    p3.addContent(strong3);
    div2.addContent(p3);
    
    if(onlineUsers != null){
      Set<String> userSet = onlineUsers.keySet();
      for(String user:userSet){
        Element p = new Element("p");
        p.setText(user);
        div2.addContent(p);
      }
    }
    
    body.addContent(div2);
    root.addContent(body);
    return root;
  }
  
  public static Element genResponse(){
    Element root = new Element("html");
    Element body = new Element("body");
    Element button = new Element("script");
    button.setText("location.href='/';");
    body.addContent(button);
    root.addContent(body);
    return root;
  }
  
  private static Element genBtn(String btnName, String href){
    Element btn = new Element("button");
    btn.setText(btnName);
    btn.setAttribute("style", "margin:2px; width:80px; height:40px; border:#F00 2px; background:#2f435e; color:#FFF; border-radius:3px; font-size:18px");
    btn.setAttribute("onclick", "{if(confirm('Are you sure "+btnName+"?'))location.href='/"+href+"'}");
    return btn;
    
  }

}
